package main.java.com.lee.thread;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @Description TODO
 * @Author winston
 * @DateTime 2021/12/8
 */
public class PoolHookTest {
	public static void main(String[] args) {
		testHook();
	}

	private static void testHook() {

		ThreadLocal<Long> local = new ThreadLocal<>();

		ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(4, 5, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(100)) {


			@Override

			protected void beforeExecute(Thread t, Runnable r) {
				super.beforeExecute(t, r);
				local.set(System.currentTimeMillis());
			}

			@Override
			protected void afterExecute(Runnable r, Throwable t) {
				super.afterExecute(r, t);
				Long aLong = local.get();
				long time = System.currentTimeMillis() - aLong;
				System.out.println(Thread.currentThread().getName()+":   "+time);
				local.remove();
			}

			@Override
			protected void terminated() {
				super.terminated();
				System.out.println(Thread.currentThread().getName() + "结束");
			}
		};


		IntStream.rangeClosed(1, 3).forEach(i ->
				threadPoolExecutor.submit(() -> {
					System.out.println(i);
					try {
						Thread.sleep(i * 1000L);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}));
		threadPoolExecutor.shutdown();
	}
}
